package com.qingcheng.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.system.Admin;
import com.qingcheng.service.system.AdminService;
import com.qingcheng.service.system.ResourceService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by yuanxin
 * Date:2019/6/30
 * Time:10:13
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    @Reference
    private AdminService adminService;
    @Reference
    private ResourceService resourceService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //查询管理员
        HashMap map = new HashMap();
        map.put("loginName",s);
        map.put("status","1");
        List<Admin> list = adminService.findList(map);
        if (list.size() == 0) {
            return null;
        }
        //构建角色集合 ，项目中此处应该是根据用户名查询用户的角色列表
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        List<String> resKeyList = resourceService.findResKeyByAdmin(s);
        for (String resKey : resKeyList) {
            grantedAuthorities.add(new SimpleGrantedAuthority(resKey));
        }
        return new User(s,list.get(0).getPassword(),grantedAuthorities);
    }
}
